<template>
  <div class="cognitive-survey">
    <div class="header">
      <h1>{{ surveyConfig.title }}</h1>
      <p class="subtitle">{{ surveyConfig.subtitle }}</p>
      <div class="header-actions">
        <button @click="goToHome" class="home-btn">
          <span class="home-icon">🏠</span> {{ surveyConfig.ui.buttons.home }}
        </button>
        <button @click="showSettings = true" class="settings-btn">
          <span class="settings-icon">⚙️</span> {{ surveyConfig.ui.buttons.settings }}
        </button>
      </div>
    </div>

    <!-- 设置页面 -->
    <div class="settings-modal" v-if="showSettings">
      <div class="settings-content">
        <div class="settings-header">
          <h2>{{ surveyConfig.settings.title }}</h2>
          <button @click="closeSettings" class="close-btn">×</button>
        </div>

        <div class="settings-form">
          <div class="form-group">
            <label>问答编号：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.surveyId" placeholder="请输入问答编号（用于区分不同组的问卷）" maxlength="20">
            <p class="field-hint">编号用于区分不同组的问卷，建议使用如：COG001、COGNITIVE_A等格式</p>
          </div>
          <div class="form-group">
            <label>记录人姓名：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.name" placeholder="请输入记录人姓名">
          </div>
          <div class="form-group">
            <label>记录人职务/身份：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.position" placeholder="请输入职务或身份（如：医生、护士、研究员等）">
          </div>
          <div class="form-group">
            <label>所属机构：</label>
            <input type="text" v-model="recorderInfo.institution" placeholder="请输入所属医院或机构名称">
          </div>
          <div class="form-group">
            <label>联系方式：</label>
            <input type="text" v-model="recorderInfo.contact" placeholder="请输入联系电话或邮箱">
          </div>
          <div class="form-group">
            <label>默认备注：</label>
            <textarea v-model="recorderInfo.defaultRemarks" placeholder="请输入默认备注信息（可选）" rows="3"></textarea>
          </div>
        </div>

        <div class="settings-actions">
          <button @click="saveRecorderInfo" class="save-settings-btn">保存设置</button>
          <button @click="closeSettings" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>

    <!-- 记录人信息显示 -->
    <div class="recorder-info-display" v-if="recorderInfo.name && !showSettings && !showResult && !showExport">
      <div class="recorder-card">
        <div class="recorder-main-info">
          <h3>问答编号：{{ recorderInfo.surveyId }}</h3>
          <p>记录人：{{ recorderInfo.name }} | {{ recorderInfo.position }}</p>
          <p v-if="recorderInfo.institution">{{ recorderInfo.institution }}</p>
        </div>
        <div class="recorder-actions">
          <button @click="showSettings = true" class="edit-recorder-btn">编辑</button>
          <button @click="showExportDialog" class="export-btn">{{ surveyConfig.ui.buttons.export }}</button>
        </div>
      </div>
    </div>

    <!-- 导出数据模态框 -->
    <div class="export-modal" v-if="showExport">
      <div class="export-content">
        <div class="export-header">
          <h2>{{ surveyConfig.export.title }}</h2>
          <button @click="closeExport" class="close-btn">×</button>
        </div>

        <div class="export-form">
          <div class="export-info">
            <p><strong>当前问答编号：</strong>{{ recorderInfo.surveyId }}</p>
            <p><strong>导出说明：</strong>将从服务器打包当前编号的所有认知能力评估数据</p>
          </div>

          <div class="form-group">
            <label>导出密码：<span class="required">*</span></label>
            <input type="password" v-model="exportPassword" placeholder="请输入导出密码" @keyup.enter="exportData">
            <p class="field-hint">请联系管理员获取导出密码</p>
          </div>

          <div class="export-options">
            <div class="form-group">
              <label>
                <input type="checkbox" v-model="exportOptions.includeRawData">
                包含原始评估数据
              </label>
            </div>
            <div class="form-group">
              <label>
                <input type="checkbox" v-model="exportOptions.includeStatistics">
                包含统计分析
              </label>
            </div>
          </div>
        </div>

        <div class="export-actions">
          <button @click="exportData" class="export-confirm-btn" :disabled="!exportPassword">
            <span v-if="!isExporting">导出压缩包</span>
            <span v-else>导出中...</span>
          </button>
          <button @click="closeExport" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>

    <div class="survey-form" v-if="!showResult && !showSettings && !showExport">
      <p class="instruction">{{ surveyConfig.instruction }}</p>

      <!-- 被评估人基本信息 -->
      <div class="section">
        <h2>{{ surveyConfig.sections.basicInfo.title }}</h2>
        <div class="form-grid">
          <div class="form-group" v-for="field in surveyConfig.sections.basicInfo.fields" :key="field.name">
            <label>{{ field.label }}：<span v-if="field.required" class="required">*</span></label>
            <input
              v-if="field.type === 'text' || field.type === 'number' || field.type === 'tel' || field.type === 'date' || field.type === 'datetime-local'"
              :type="field.type" v-model="formData[field.name]" :placeholder="field.placeholder" :min="field.min"
              :max="field.max" :step="field.step">
            <textarea v-else-if="field.type === 'textarea'" v-model="formData[field.name]"
              :placeholder="field.placeholder" :rows="field.rows"></textarea>
            <div v-else-if="field.type === 'radio'" class="radio-group">
              <label v-for="option in field.options" :key="option.value">
                <input type="radio" v-model="formData[field.name]" :value="option.value"> {{ option.label }}
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- 认知能力评估 -->
      <div class="section">
        <h2>{{ surveyConfig.sections.assessment.title }}</h2>
        <p class="assessment-description">{{ surveyConfig.sections.assessment.description }}</p>

        <!-- 表单组 - 合并显示所有组 -->
        <div class="form-groups">
          <div v-for="group in surveyConfig.formGroups" :key="group.id" class="form-group-section">
            <div class="group-header">
              <h3>{{ group.title }}</h3>
              <p v-if="group.description" class="group-description">{{ group.description }}</p>
            </div>

            <div class="questions">
              <div v-for="question in group.questions" :key="question.id" class="question-item">
                <label class="question-label">
                  {{ question.label }}
                  <span v-if="question.required" class="required">*</span>
                </label>
                <p v-if="question.description" class="question-description">{{ question.description }}</p>

                <!-- 单选按钮 -->
                <div v-if="question.type === 'radio'" class="radio-group">
                  <label v-for="option in question.options" :key="option.value" class="radio-option">
                    <input type="radio" :name="question.id" :value="option.value" v-model="formData[question.id]" @change="getAttentionScore()">
                    <span class="radio-label">{{ option.label }}</span>
                  </label>
                </div>

                <!-- 复选框 -->
                <div v-else-if="question.type === 'checkbox'" class="checkbox-group">
                  <label class="checkbox-option">
                    <input type="checkbox" v-model="formData[question.id]" @change="getAttentionScore()">
                    <span>已记住</span>
                  </label>
                </div>

                <!-- 数字输入 -->
                <div v-else-if="question.type === 'number'" class="number-input-group">
                  <input type="number" v-model.number="formData[question.id]" :placeholder="question.placeholder"
                    :min="question.min" :max="question.max" class="form-input number-input">
                  <span v-if="question.unit" class="input-unit">{{ question.unit }}</span>
                </div>

                <!-- 文本输入 -->
                <input v-else-if="question.type === 'text'" type="text" v-model="formData[question.id]"
                  :placeholder="question.placeholder" class="form-input">

                <!-- 文本域 -->
                <textarea v-else-if="question.type === 'textarea'" v-model="formData[question.id]"
                  :placeholder="question.placeholder" class="form-textarea" :rows="question.rows || 3"></textarea>

                <!-- 只读显示字段 -->
                <div v-else-if="question.type === 'display'" class="display-field">
                  <span class="display-value">{{ getAttentionScore() }}</span>
                  <span class="display-unit">分</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <button @click="calculateResult" class="submit-btn" :disabled="!isFormValid">
            {{ surveyConfig.ui.buttons.submit }}
          </button>
        </div>
      </div>
    </div>

    <!-- 结果展示 -->
    <div class="result-section" v-if="showResult">
      <h2>认知能力评估结果</h2>
      <div class="result-card">
        <div class="result-summary">
          <h3>{{ result.cognitiveLevelName }}</h3>
          <p class="score">总分：{{ result.totalScore }}/{{ result.maxScore }} ({{ result.percentage }}%)</p>
          <p class="diagnosis">{{ result.diagnosis }}</p>
        </div>

        <div class="result-details">
          <h4>各维度得分详情：</h4>
          <ul>
            <li>
              <strong>1. 注意：</strong>{{ result.dimensions.attention.total }}/{{ result.dimensions.attention.max }}
              ({{ result.dimensions.attention.percentage }}%) - {{ result.dimensions.attention.level }}
            </li>
            <li>
              <strong>2. 执行功能/言语：</strong>{{ result.dimensions.executive.total }}/{{ result.dimensions.executive.max }}
              ({{ result.dimensions.executive.percentage }}%) - {{ result.dimensions.executive.level }}
              <span v-if="formData.animalNamesCount">（说出{{ formData.animalNamesCount }}个动物名字）</span>
            </li>
            <li>
              <strong>3. 定向：</strong>{{ result.dimensions.orientation.total }}/{{ result.dimensions.orientation.max }}
              ({{ result.dimensions.orientation.percentage }}%) - {{ result.dimensions.orientation.level }}
            </li>
            <li>
              <strong>4. 记忆：</strong>{{ result.dimensions.memory.total }}/{{ result.dimensions.memory.max }}
              ({{ result.dimensions.memory.percentage }}%) - {{ result.dimensions.memory.level }}
              <br>
              <span style="font-size: 0.9em; color: #666;">
                无提示：{{ result.dimensions.memory.noHintScore }}/5，
                分类提示：{{ result.dimensions.memory.categoryHintScore }}/5，
                多选提示：{{ result.dimensions.memory.multipleChoiceScore }}/5
              </span>
            </li>
            <li>
              <strong>5. 计算能力：</strong>{{ result.dimensions.calculation.total }}/{{ result.dimensions.calculation.max }}
              ({{ result.dimensions.calculation.percentage }}%) - {{ result.dimensions.calculation.level }}
            </li>
          </ul>
        </div>

        <div class="result-recommendations" v-if="result.recommendations && result.recommendations.length > 0">
          <h4>建议措施：</h4>
          <ul>
            <li v-for="(recommendation, index) in result.recommendations" :key="index">{{ recommendation }}</li>
          </ul>
        </div>

        <div class="action-buttons">
          <button @click="saveToBackendOnly" class="save-btn" :disabled="isSaving">
            <span v-if="!isSaving">保存结果</span>
            <span v-else>保存中...</span>
          </button>
          <button @click="resetForm" class="reset-btn">{{ surveyConfig.ui.buttons.restart }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { cognitiveConfig } from '@/config/cognitiveConfig.js';
import { calculateCognitiveAssessment } from '@/config/cognitiveLogic.js';

export default {
  name: 'CognitiveSurvey',
  mounted() {
    // 加载记录人信息
    this.loadRecorderInfo();

    // 初始化表单数据
    this.initializeForm();
    
    // 自动设置当前日期（在初始化之后设置，避免被覆盖）
    if (!this.formData.recordTime) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      // 评估日期使用date类型，格式为 YYYY-MM-DD
      this.formData.recordTime = `${year}-${month}-${day}`;
    }
  },
  data() {
    return {
      surveyConfig: cognitiveConfig,
      showResult: false,
      showSettings: false,
      showExport: false,
      isExporting: false,
      isSaving: false,
      exportPassword: '',
      // 记录人信息（设置）
      recorderInfo: {
        surveyId: '',
        name: '',
        position: '',
        institution: '',
        contact: '',
        defaultRemarks: ''
      },
      // 导出选项
      exportOptions: {
        includeRawData: true,
        includeStatistics: true
      },
      // 问卷表单数据
      formData: {},
      result: {
        totalScore: 0,
        maxScore: 90,
        percentage: '0',
        cognitiveLevel: '',
        cognitiveLevelName: '',
        cognitiveLevelDescription: '',
        diagnosis: '',
        recommendations: [],
        dimensions: {},
        summary: ''
      }
    }
  },
  computed: {
    isFormValid() {
      // 检查基本信息
      if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
        return false;
      }
      // 个人信息字段已改为选填，不再进行必填验证
      
      // 自动计算注意得分
      this.getAttentionScore();
      
      // 检查所有评估项目是否已填写（根据新的配置）
      const requiredQuestions = [
        'animalNamesCount',
        'orientationYear', 'orientationMonth', 'orientationDay', 'orientationWeekday', 'orientationLocation', 'orientationCity', 'orientationScore',
        'memoryNoHintScore', 'memoryCategoryHintScore', 'memoryMultipleChoiceScore',
        'calculationScore'
      ];
      
      for (const questionId of requiredQuestions) {
        if (this.formData[questionId] === undefined || this.formData[questionId] === null || this.formData[questionId] === '') {
          return false;
        }
      }
      
      // 检查至少选择了一个注意词语的状态（记住或记不住）
      if (!this.formData.attentionWord1 && !this.formData.attentionWord2 && !this.formData.attentionWord3 && 
          !this.formData.attentionWord4 && !this.formData.attentionWord5) {
        return false;
      }
      
      return true;
    }
  },
  methods: {
    // 导航方法
    goToHome() {
      this.$router.push('/');
    },

    // 初始化表单数据
    initializeForm() {
      // 保留已设置的recordTime值
      const existingRecordTime = this.formData.recordTime;

      this.formData = {
        recordTime: existingRecordTime || ''
      };

      // 初始化所有字段为空值
      this.surveyConfig.formGroups.forEach(group => {
        group.questions.forEach(question => {
          if (!Object.prototype.hasOwnProperty.call(this.formData, question.id)) {
            this.formData[question.id] = question.type === 'number' ? null : '';
          }
        });
      });
    },

    // 设置相关方法
    saveRecorderInfo() {
      // 验证必填字段
      if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
        alert('请填写所有必填信息（问答编号、记录人姓名、职务/身份）！');
        return;
      }

      // 保存记录人信息到本地存储
      localStorage.setItem('cognitiveRecorderInfo', JSON.stringify(this.recorderInfo));
      // 设置默认备注
      if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
        this.formData.remarks = this.recorderInfo.defaultRemarks;
      }
      this.showSettings = false;
      alert('记录人信息已保存！');
    },

    closeSettings() {
      this.showSettings = false;
    },

    loadRecorderInfo() {
      // 从本地存储加载记录人信息
      const saved = localStorage.getItem('cognitiveRecorderInfo');
      if (saved) {
        this.recorderInfo = JSON.parse(saved);
        // 设置默认备注
        if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
          this.formData.remarks = this.recorderInfo.defaultRemarks;
        }
      }
    },

    // 导出相关方法
    showExportDialog() {
      this.showExport = true;
      this.exportPassword = '';
    },

    closeExport() {
      this.showExport = false;
      this.exportPassword = '';
      this.isExporting = false;
    },

    async exportData() {
      this.isExporting = true;

      try {
        // 发送导出请求到服务器
        const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/export-cognitive-survey`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            surveyId: this.recorderInfo.surveyId,
            password: this.exportPassword,
            exportOptions: this.exportOptions
          })
        });

        if (response.status === 401) {
          alert('密码错误，请重新输入！');
          return;
        }

        if (!response.ok) {
          throw new Error('导出请求失败');
        }

        // 获取服务器返回的压缩包
        const blob = await response.blob();

        if (blob.size === 0) {
          alert('当前问答编号下没有认知能力评估数据！');
          return;
        }

        // 下载服务器生成的压缩包
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `认知能力评估数据_${this.recorderInfo.surveyId}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.zip`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        alert('数据导出成功！');
        this.closeExport();
      } catch (error) {
        console.error('导出失败:', error);
        alert('导出失败，请检查网络连接或联系管理员！');
      } finally {
        this.isExporting = false;
      }
    },

    // 计算注意得分（根据选择的词语数量）
    getAttentionScore() {
      let count = 0;
      // 只计算选择"记住"的词语数量
      if (this.formData.attentionWord1 === 'remembered') count++;
      if (this.formData.attentionWord2 === 'remembered') count++;
      if (this.formData.attentionWord3 === 'remembered') count++;
      if (this.formData.attentionWord4 === 'remembered') count++;
      if (this.formData.attentionWord5 === 'remembered') count++;
      // 自动更新formData中的attentionScore
      this.formData.attentionScore = count;
      return count;
    },

    calculateResult() {
      // 确保注意得分已计算
      this.getAttentionScore();
      // 使用认知能力评估逻辑
      this.result = calculateCognitiveAssessment(this.formData);
      this.showResult = true;
    },

    async saveToBackendOnly() {
      this.isSaving = true;

      try {
        // 1. 保存问卷数据到后台
        await this.saveToBackend();

        // 2. 生成评估报告内容
        const timestamp = new Date().toLocaleString('zh-CN');
        const recordTime = this.formData.recordTime ?
          new Date(this.formData.recordTime).toLocaleString('zh-CN') :
          timestamp;

        const content = `认知能力评估结果报告
问答编号：${this.recorderInfo.surveyId}
生成时间：${timestamp}

=== 记录人信息 ===
记录人姓名：${this.recorderInfo.name}
记录人职务/身份：${this.recorderInfo.position}
所属机构：${this.recorderInfo.institution}
联系方式：${this.recorderInfo.contact}
记录时间：${recordTime}
备注：${this.formData.remarks || '无'}

=== 被评估人基本信息 ===
姓名：${this.formData.patientName}
编号：${this.formData.patientId || '未填写'}
年龄：${this.formData.age}岁
性别：${this.formData.gender === 'male' ? '男性' : '女性'}
教育程度：${this.getEducationLabel(this.formData.education)}
联系电话：${this.formData.phone || '未填写'}
测量地点：${this.formData.measurementLocation || '未填写'}
测量人员：${this.formData.measurementPerson || '未填写'}

=== 评估结果 ===
总分：${this.result.totalScore}/${this.result.maxScore} (${this.result.percentage}%)
认知功能水平：${this.result.cognitiveLevelName}
诊断结果：${this.result.diagnosis}

=== 各维度得分详情 ===
1. 注意：${this.result.dimensions.attention.total}/${this.result.dimensions.attention.max} (${this.result.dimensions.attention.percentage}%) - ${this.result.dimensions.attention.level}
2. 执行功能/言语：${this.result.dimensions.executive.total}/${this.result.dimensions.executive.max} (${this.result.dimensions.executive.percentage}%) - ${this.result.dimensions.executive.level}
   （说出${this.formData.animalNamesCount || 0}个动物名字）
3. 定向：${this.result.dimensions.orientation.total}/${this.result.dimensions.orientation.max} (${this.result.dimensions.orientation.percentage}%) - ${this.result.dimensions.orientation.level}
4. 记忆：${this.result.dimensions.memory.total}/${this.result.dimensions.memory.max} (${this.result.dimensions.memory.percentage}%) - ${this.result.dimensions.memory.level}
   无提示：${this.result.dimensions.memory.noHintScore}/5，分类提示：${this.result.dimensions.memory.categoryHintScore}/5，多选提示：${this.result.dimensions.memory.multipleChoiceScore}/5
5. 计算能力：${this.result.dimensions.calculation.total}/${this.result.dimensions.calculation.max} (${this.result.dimensions.calculation.percentage}%) - ${this.result.dimensions.calculation.level}

=== 建议措施 ===
${this.result.recommendations.map((rec, index) => `${index + 1}. ${rec}`).join('\n')}

报告结束
`;

        // 3. 保存评估报告到@data/文件夹
        await this.saveFileToDataFolder(content);

        alert('✅ 数据已成功保存到后台！\n\n📁 问卷数据：survey_data/\n📄 评估报告：@data/');

      } catch (error) {
        console.error('保存到后台失败:', error);
        alert('❌ 保存失败，请检查网络连接或联系管理员！\n\n错误信息：' + error.message);
      } finally {
        this.isSaving = false;
      }
    },

    getEducationLabel(value) {
      const map = {
        'illiterate': '文盲',
        'primary': '小学',
        'middle': '初中',
        'high': '高中/中专',
        'college': '大专',
        'university': '本科',
        'graduate': '研究生及以上'
      };
      return map[value] || '未填写';
    },

    async saveToBackend() {
      // 构建符合CognitiveSurveyData模型的数据格式
      const surveyData = {
        surveyId: this.recorderInfo.surveyId,
        recordTime: new Date().toISOString(),
        recorderName: this.recorderInfo.name,
        recorderPosition: this.recorderInfo.position,
        recorderInstitution: this.recorderInfo.institution,
        recorderContact: this.recorderInfo.contact,
        patientName: this.formData.patientName || "未填写",
        patientId: this.formData.patientId,
        age: this.formData.age || 0,
        gender: this.formData.gender,
        education: this.formData.education,
        phone: this.formData.phone,
        measurementLocation: this.formData.measurementLocation,
        measurementPerson: this.formData.measurementPerson,
        remarks: this.formData.remarks,
        // 1. 注意
        attentionWord1: this.formData.attentionWord1 || '',
        attentionWord2: this.formData.attentionWord2 || '',
        attentionWord3: this.formData.attentionWord3 || '',
        attentionWord4: this.formData.attentionWord4 || '',
        attentionWord5: this.formData.attentionWord5 || '',
        attentionScore: parseInt(this.formData.attentionScore) || 0,
        // 2. 执行功能/言语
        animalNamesCount: parseInt(this.formData.animalNamesCount) || 0,
        animalNamesList: this.formData.animalNamesList,
        // 3. 定向
        orientationYear: parseInt(this.formData.orientationYear),
        orientationMonth: parseInt(this.formData.orientationMonth),
        orientationDay: parseInt(this.formData.orientationDay),
        orientationWeekday: this.formData.orientationWeekday,
        orientationLocation: this.formData.orientationLocation,
        orientationCity: this.formData.orientationCity,
        orientationScore: parseInt(this.formData.orientationScore) || 0,
        // 4. 记忆
        memoryNoHint: this.formData.memoryNoHint,
        memoryNoHintScore: parseInt(this.formData.memoryNoHintScore) || 0,
        memoryCategoryHint: this.formData.memoryCategoryHint,
        memoryCategoryHintScore: parseInt(this.formData.memoryCategoryHintScore) || 0,
        memoryMultipleChoice: this.formData.memoryMultipleChoice,
        memoryMultipleChoiceScore: parseInt(this.formData.memoryMultipleChoiceScore) || 0,
        // 5. 计算能力
        calculationQuestion1: this.formData.calculationQuestion1,
        calculationAnswer1: this.formData.calculationAnswer1,
        calculationQuestion2: this.formData.calculationQuestion2,
        calculationAnswer2: this.formData.calculationAnswer2,
        calculationQuestion3: this.formData.calculationQuestion3,
        calculationAnswer3: this.formData.calculationAnswer3,
        calculationScore: parseInt(this.formData.calculationScore) || 0,
        // 计算结果
        totalScore: this.result.totalScore,
        maxScore: this.result.maxScore,
        percentage: parseFloat(this.result.percentage),
        cognitiveLevel: this.result.cognitiveLevel,
        cognitiveLevelName: this.result.cognitiveLevelName,
        diagnosis: this.result.diagnosis,
        recommendations: this.result.recommendations,
        dimensions: this.result.dimensions,
        createdAt: new Date().toISOString()
      };

      const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-cognitive-survey`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(surveyData)
      });

      if (!response.ok) {
        throw new Error('保存问卷数据失败');
      }
    },

    async saveFileToDataFolder(content) {
      // 通过API保存文件到@data/文件夹
      const filename = `认知能力评估结果_${this.recorderInfo.surveyId}_${this.formData.patientName}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;

      const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-file`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          filename: filename,
          content: content,
          surveyId: this.recorderInfo.surveyId
        })
      });

      if (!response.ok) {
        throw new Error('保存评估报告失败');
      }
    },

    resetForm() {
      this.formData = {};
      this.result = {
        totalScore: 0,
        maxScore: 90,
        percentage: '0',
        cognitiveLevel: '',
        cognitiveLevelName: '',
        cognitiveLevelDescription: '',
        diagnosis: '',
        recommendations: [],
        dimensions: {},
        summary: ''
      };
      this.showResult = false;
      this.initializeForm();
    }
  }
}
</script>

<style scoped>
.cognitive-survey {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.header h1 {
  margin: 0 0 10px 0;
  font-size: 2.5em;
  font-weight: 300;
}

.subtitle {
  margin: 0 0 20px 0;
  font-size: 1.2em;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.home-btn,
.settings-btn {
  padding: 10px 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.home-btn:hover,
.settings-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-2px);
}

/* 设置模态框样式 */
.settings-modal,
.export-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.settings-content,
.export-content {
  background: white;
  padding: 30px;
  border-radius: 15px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.settings-header,
.export-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 5px;
  border-radius: 50%;
  width: 35px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: #f0f0f0;
  color: #333;
}

/* 记录人信息显示 */
.recorder-info-display {
  margin-bottom: 30px;
}

.recorder-card {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 4px solid #667eea;
}

.recorder-main-info h3 {
  margin: 0 0 5px 0;
  color: #333;
}

.recorder-main-info p {
  margin: 5px 0;
  color: #666;
}

.recorder-actions {
  display: flex;
  gap: 10px;
}

.edit-recorder-btn,
.export-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.edit-recorder-btn:hover {
  background: #f0f0f0;
}

.export-btn {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.export-btn:hover {
  background: #218838;
}

/* 表单样式 */
.instruction {
  background: #e7f3ff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #007bff;
  color: #333;
}

.section {
  background: white;
  padding: 30px;
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.section h2 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 1.8em;
  border-bottom: 2px solid #667eea;
  padding-bottom: 10px;
}

.assessment-description {
  color: #666;
  font-style: italic;
  margin-bottom: 20px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.required {
  color: #dc3545;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.field-hint {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.radio-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.radio-option:hover {
  border-color: #667eea;
  background: #f8f9ff;
}

.radio-option input[type="radio"] {
  width: auto;
}

/* 复选框样式 */
.checkbox-group {
  margin-top: 10px;
}

.checkbox-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.checkbox-option:hover {
  border-color: #667eea;
  background: #f8f9ff;
}

.checkbox-option input[type="checkbox"] {
  width: auto;
}

/* 数字输入组 */
.number-input-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.number-input {
  flex: 1;
}

.input-unit {
  color: #666;
  font-size: 14px;
}

/* 文本输入样式 */
.form-input {
  width: 100%;
  padding: 12px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 文本域样式 */
.form-textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;
  font-family: inherit;
}

.form-textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 只读显示字段样式 */
.display-field {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #f8f9fa;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
}

.display-value {
  font-size: 18px;
  font-weight: bold;
  color: #667eea;
}

.display-unit {
  color: #666;
  font-size: 14px;
}

/* 表单组 */
.form-group-section {
  margin-bottom: 40px;
  padding-bottom: 30px;
  border-bottom: 2px solid #e1e5e9;
}

.form-group-section:last-child {
  border-bottom: none;
  margin-bottom: 20px;
}

.group-header h3 {
  color: #667eea;
  margin-bottom: 10px;
}

.group-description {
  color: #666;
  font-style: italic;
  margin-bottom: 20px;
}

.question-item {
  margin-bottom: 25px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.question-label {
  font-weight: 500;
  margin-bottom: 10px;
  display: block;
}

.question-description {
  color: #666;
  font-size: 0.9em;
  margin-bottom: 15px;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  padding: 20px;
}

.submit-btn {
  padding: 15px 40px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 18px;
  background: #667eea;
  color: white;
  transition: all 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  background: #5a67d8;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 结果展示样式 */
.result-section {
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.result-card {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 10px;
  border-left: 4px solid #28a745;
}

.result-summary {
  text-align: center;
  margin-bottom: 25px;
}

.result-summary h3 {
  color: #28a745;
  margin-bottom: 10px;
  font-size: 1.5em;
}

.score {
  font-size: 1.2em;
  font-weight: bold;
  color: #333;
  margin: 10px 0;
}

.diagnosis {
  font-size: 1.1em;
  color: #666;
  margin-top: 10px;
}

.result-details ul {
  list-style: none;
  padding: 0;
}

.result-details li {
  padding: 8px 0;
  border-bottom: 1px solid #e1e5e9;
}

.result-recommendations {
  margin-top: 20px;
  padding: 15px;
  background: #fff3cd;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
}

.result-recommendations h4 {
  margin-top: 0;
  color: #856404;
}

.result-recommendations ul {
  list-style: disc;
  padding-left: 20px;
  color: #856404;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 25px;
}

.save-btn,
.reset-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
}

.save-btn {
  background: #28a745;
  color: white;
}

.save-btn:hover {
  background: #218838;
}

.save-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.reset-btn {
  background: #6c757d;
  color: white;
}

.reset-btn:hover {
  background: #5a6268;
}

/* 设置和导出按钮样式 */
.settings-actions,
.export-actions {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  margin-top: 25px;
}

.save-settings-btn,
.export-confirm-btn {
  background: #667eea;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.save-settings-btn:hover,
.export-confirm-btn:hover {
  background: #5a67d8;
}

.export-confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.cancel-btn {
  background: #6c757d;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #5a6268;
}

.export-info {
  background: #e7f3ff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #007bff;
}

.export-options {
  margin: 20px 0;
}

.export-options .form-group {
  margin-bottom: 10px;
}

.export-options label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.export-options input[type="checkbox"] {
  width: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cognitive-survey {
    padding: 10px;
  }

  .header h1 {
    font-size: 2em;
  }

  .header-actions {
    flex-direction: column;
    gap: 10px;
  }

  .settings-content,
  .export-content {
    width: 95%;
    padding: 20px;
  }

  .recorder-card {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>

